<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Extensibility - Zend Framework Manual</title>

    <link href="../css/shCore.css" rel="stylesheet" type="text/css" />
    <link href="../css/shThemeDefault.css" rel="stylesheet" type="text/css" />
    <link href="../css/styles.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Zend Framework</h1>
<h2>Programmer's Reference Guide</h2>
<ul>
    <li><a href="../en/zend.search.lucene.extending.html">Inglês (English)</a></li>
    <li><a href="../pt-br/zend.search.lucene.extending.html">Português Brasileiro (Brazilian Portuguese)</a></li>
</ul>
<table width="100%">
    <tr valign="top">
        <td width="85%">
            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.search.lucene.charset.html">Character Set</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.search.lucene.html">Zend_Search_Lucene</a></span><br />
                        <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.search.lucene.java-lucene.html">Interoperating with Java Lucene</a></div>
                    </td>
                </tr>
            </table>
<hr />
<div id="zend.search.lucene.extending" class="section"><div class="info"><h1 class="title">Extensibility</h1></div>
    

    <div class="section" id="zend.search.lucene.extending.analysis"><div class="info"><h1 class="title">Text Analysis</h1></div>
        

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_Analyzer</span> class is used by the
            indexer to tokenize document text fields.
        </p>

        <p class="para">
            The  <span class="methodname">Zend_Search_Lucene_Analysis_Analyzer::getDefault()</span> and
            <code class="code">Zend_Search_Lucene_Analysis_Analyzer::setDefault()</code> methods are used
            to get and set the default analyzer.
        </p>

        <p class="para">
            You can assign your own text analyzer or choose it from the set of predefined analyzers:
            <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common_Text</span> and
            <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</span>
            (default). Both of them interpret tokens as sequences of letters.
            <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</span>
            converts all tokens to lower case.
        </p>

        <p class="para">
            To switch between analyzers:
        </p>

        <pre class="programlisting brush: php">
Zend_Search_Lucene_Analysis_Analyzer::setDefault(
    new Zend_Search_Lucene_Analysis_Analyzer_Common_Text());
...
$index-&gt;addDocument($doc);
</pre>


        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common</span> class is designed
            to be an ancestor of all user defined analyzers. User should only define the
             <span class="methodname">reset()</span> and  <span class="methodname">nextToken()</span> methods, which
            takes its string from the $_input member and returns tokens one by one (a
            <b><tt>NULL</tt></b> value indicates the end of the stream).
        </p>

        <p class="para">
            The  <span class="methodname">nextToken()</span> method should call the
             <span class="methodname">normalize()</span> method on each token. This will allow you to use
            token filters with your analyzer.
        </p>

        <p class="para">
            Here is an example of a custom analyzer, which accepts words with digits as terms:

            <div class="example" id="zend.search.lucene.extending.analysis.example-1"><div class="info"><p><b>Example #1 Custom text Analyzer</b></p></div>
                

                <pre class="programlisting brush: php">
/**
 * Here is a custom text analyser, which treats words with digits as
 * one term
 */

class My_Analyzer extends Zend_Search_Lucene_Analysis_Analyzer_Common
{
    private $_position;

    /**
     * Reset token stream
     */
    public function reset()
    {
        $this-&gt;_position = 0;
    }

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    public function nextToken()
    {
        if ($this-&gt;_input === null) {
            return null;
        }

        while ($this-&gt;_position &lt; strlen($this-&gt;_input)) {
            // skip white space
            while ($this-&gt;_position &lt; strlen($this-&gt;_input) &amp;&amp;
                   !ctype_alnum( $this-&gt;_input[$this-&gt;_position] )) {
                $this-&gt;_position++;
            }

            $termStartPosition = $this-&gt;_position;

            // read token
            while ($this-&gt;_position &lt; strlen($this-&gt;_input) &amp;&amp;
                   ctype_alnum( $this-&gt;_input[$this-&gt;_position] )) {
                $this-&gt;_position++;
            }

            // Empty token, end of stream.
            if ($this-&gt;_position == $termStartPosition) {
                return null;
            }

            $token = new Zend_Search_Lucene_Analysis_Token(
                                      substr($this-&gt;_input,
                                             $termStartPosition,
                                             $this-&gt;_position -
                                             $termStartPosition),
                                      $termStartPosition,
                                      $this-&gt;_position);
            $token = $this-&gt;normalize($token);
            if ($token !== null) {
                return $token;
            }
            // Continue if token is skipped
        }

        return null;
    }
}

Zend_Search_Lucene_Analysis_Analyzer::setDefault(
    new My_Analyzer());
</pre>

            </div>
        </p>
    </div>

    <div class="section" id="zend.search.lucene.extending.filters"><div class="info"><h1 class="title">Tokens Filtering</h1></div>
        

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common</span> analyzer also
            offers a token filtering mechanism.
        </p>

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter</span> class provides an
            abstract interface for such filters. Your own filters should extend this class either
            directly or indirectly.
        </p>

        <p class="para">
            Any custom filter must implement the  <span class="methodname">normalize()</span> method which
            may transform input token or signal that the current token should be skipped.
        </p>

        <p class="para">
            There are three filters already defined in the analysis subpackage:

            <ul class="itemizedlist">
                <li class="listitem">
                    <p class="para">
                        <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter_LowerCase</span>
                    </p>
                </li>

                <li class="listitem">
                    <p class="para">
                        <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter_ShortWords</span>
                    </p>
                </li>

                <li class="listitem">
                    <p class="para">
                        <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter_StopWords</span>
                    </p>
                </li>
            </ul>
        </p>

        <p class="para">
            The <code class="code">LowerCase</code> filter is already used for
            <span class="classname">Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</span>
            analyzer by default.
        </p>

        <p class="para">
            The <code class="code">ShortWords</code> and <code class="code">StopWords</code> filters may be used with
            pre-defined or custom analyzers like this:
        </p>

        <pre class="programlisting brush: php">
$stopWords = array(&#039;a&#039;, &#039;an&#039;, &#039;at&#039;, &#039;the&#039;, &#039;and&#039;, &#039;or&#039;, &#039;is&#039;, &#039;am&#039;);
$stopWordsFilter =
    new Zend_Search_Lucene_Analysis_TokenFilter_StopWords($stopWords);

$analyzer =
    new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
$analyzer-&gt;addFilter($stopWordsFilter);

Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
</pre>


        <pre class="programlisting brush: php">
$shortWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_ShortWords();

$analyzer =
    new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
$analyzer-&gt;addFilter($shortWordsFilter);

Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
</pre>


        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter_StopWords</span> constructor
            takes an array of stop-words as an input. But stop-words may be also loaded from a file:
        </p>

        <pre class="programlisting brush: php">
$stopWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_StopWords();
$stopWordsFilter-&gt;loadFromFile($my_stopwords_file);

$analyzer =
   new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
$analyzer-&gt;addFilter($stopWordsFilter);

Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
</pre>


        <p class="para">
            This file should be a common text file with one word in each line. The &#039;#&#039; character
            marks a line as a comment.
        </p>

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Analysis_TokenFilter_ShortWords</span>
            constructor has one optional argument. This is the word length limit, set by default to
            2.
        </p>
    </div>

    <div class="section" id="zend.search.lucene.extending.scoring"><div class="info"><h1 class="title">Scoring Algorithms</h1></div>
        

        <p class="para">
            The score of a document <i>d</i> for a query <i>q</i>
            is defined as follows:
        </p>

        <p class="para">
            <code class="code">score(q,d) = sum( tf(t in d) * idf(t) * getBoost(t.field in d) *
                lengthNorm(t.field in d) ) * coord(q,d) * queryNorm(q)</code>
        </p>

        <p class="para">
            tf(t in d) -  <span class="methodname">Zend_Search_Lucene_Search_Similarity::tf($freq)</span> -
            a score factor based on the frequency of a term or phrase in a document.
        </p>

        <p class="para">
            idf(t) -  <span class="methodname">Zend_Search_Lucene_Search_Similarity::idf($input,
                $reader)</span> - a score factor for a simple term with the specified index.
        </p>

        <p class="para">
            getBoost(t.field in d) - the boost factor for the term field.
        </p>

        <p class="para">
            lengthNorm($term) - the normalization value for a field given the total
            number of terms contained in a field. This value is stored within the index.
            These values, together with field boosts, are stored in an index and multiplied
            into scores for hits on each field by the search code.
        </p>

        <p class="para">
            Matches in longer fields are less precise, so implementations of this method usually
            return smaller values when numTokens is large, and larger values when numTokens is
            small.
        </p>

        <p class="para">
            coord(q,d) -  <span class="methodname">Zend_Search_Lucene_Search_Similarity::coord($overlap,
                $maxOverlap)</span> - a score factor based on the fraction of all query terms
            that a document contains.
        </p>

        <p class="para">
            The presence of a large portion of the query terms indicates a better match
            with the query, so implementations of this method usually return larger values
            when the ratio between these parameters is large and smaller values when
            the ratio between them is small.
        </p>

        <p class="para">
            queryNorm(q) - the normalization value for a query given the sum of the squared weights
            of each of the query terms. This value is then multiplied into the weight of each query
            term.
        </p>

        <p class="para">
            This does not affect ranking, but rather just attempts to make scores from different
            queries comparable.
        </p>

        <p class="para">
            The scoring algorithm can be customized by defining your own Similarity class. To do
            this extend the <span class="classname">Zend_Search_Lucene_Search_Similarity</span> class as
            defined below, then use the
            <span class="classname">Zend_Search_Lucene_Search_Similarity::setDefault($similarity);</span>
            method to set it as default.
        </p>

        <pre class="programlisting brush: php">
class MySimilarity extends Zend_Search_Lucene_Search_Similarity {
    public function lengthNorm($fieldName, $numTerms) {
        return 1.0/sqrt($numTerms);
    }

    public function queryNorm($sumOfSquaredWeights) {
        return 1.0/sqrt($sumOfSquaredWeights);
    }

    public function tf($freq) {
        return sqrt($freq);
    }

    /**
     * It&#039;s not used now. Computes the amount of a sloppy phrase match,
     * based on an edit distance.
     */
    public function sloppyFreq($distance) {
        return 1.0;
    }

    public function idfFreq($docFreq, $numDocs) {
        return log($numDocs/(float)($docFreq+1)) + 1.0;
    }

    public function coord($overlap, $maxOverlap) {
        return $overlap/(float)$maxOverlap;
    }
}

$mySimilarity = new MySimilarity();
Zend_Search_Lucene_Search_Similarity::setDefault($mySimilarity);
</pre>

    </div>

    <div class="section" id="zend.search.lucene.extending.storage"><div class="info"><h1 class="title">Storage Containers</h1></div>
        

        <p class="para">
            The abstract class <span class="classname">Zend_Search_Lucene_Storage_Directory</span> defines
            directory functionality.
        </p>

        <p class="para">
            The <span class="classname">Zend_Search_Lucene</span> constructor uses either a string or a
            <span class="classname">Zend_Search_Lucene_Storage_Directory</span> object as an input.
        </p>

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Storage_Directory_Filesystem</span> class
            implements directory functionality for a file system.
        </p>

        <p class="para">
            If a string is used as an input for the <span class="classname">Zend_Search_Lucene</span>
            constructor, then the index reader (<span class="classname">Zend_Search_Lucene</span> object)
            treats it as a file system path and instantiates the
            <span class="classname">Zend_Search_Lucene_Storage_Directory_Filesystem</span> object.
        </p>

        <p class="para">
            You can define your own directory implementation by extending the
            <span class="classname">Zend_Search_Lucene_Storage_Directory</span> class.
        </p>

        <p class="para">
            <span class="classname">Zend_Search_Lucene_Storage_Directory</span> methods:
        </p>

        <pre class="programlisting brush: php">
abstract class Zend_Search_Lucene_Storage_Directory {
/**
 * Closes the store.
 *
 * @return void
 */
abstract function close();

/**
 * Creates a new, empty file in the directory with the given $filename.
 *
 * @param string $name
 * @return void
 */
abstract function createFile($filename);

/**
 * Removes an existing $filename in the directory.
 *
 * @param string $filename
 * @return void
 */
abstract function deleteFile($filename);

/**
 * Returns true if a file with the given $filename exists.
 *
 * @param string $filename
 * @return boolean
 */
abstract function fileExists($filename);

/**
 * Returns the length of a $filename in the directory.
 *
 * @param string $filename
 * @return integer
 */
abstract function fileLength($filename);

/**
 * Returns the UNIX timestamp $filename was last modified.
 *
 * @param string $filename
 * @return integer
 */
abstract function fileModified($filename);

/**
 * Renames an existing file in the directory.
 *
 * @param string $from
 * @param string $to
 * @return void
 */
abstract function renameFile($from, $to);

/**
 * Sets the modified time of $filename to now.
 *
 * @param string $filename
 * @return void
 */
abstract function touchFile($filename);

/**
 * Returns a Zend_Search_Lucene_Storage_File object for a given
 * $filename in the directory.
 *
 * @param string $filename
 * @return Zend_Search_Lucene_Storage_File
 */
abstract function getFileObject($filename);

}
</pre>


        <p class="para">
            The  <span class="methodname">getFileObject($filename)</span> method of a
            <span class="classname">Zend_Search_Lucene_Storage_Directory</span> instance returns a
            <span class="classname">Zend_Search_Lucene_Storage_File</span> object.
        </p>

        <p class="para">
            The <span class="classname">Zend_Search_Lucene_Storage_File</span> abstract class implements
            file abstraction and index file reading primitives.
        </p>

        <p class="para">
            You must also extend <span class="classname">Zend_Search_Lucene_Storage_File</span> for your
            directory implementation.
        </p>

        <p class="para">
            Only two methods of <span class="classname">Zend_Search_Lucene_Storage_File</span> must be
            overridden in your implementation:
        </p>

        <pre class="programlisting brush: php">
class MyFile extends Zend_Search_Lucene_Storage_File {
    /**
     * Sets the file position indicator and advances the file pointer.
     * The new position, measured in bytes from the beginning of the file,
     * is obtained by adding offset to the position specified by whence,
     * whose values are defined as follows:
     * SEEK_SET - Set position equal to offset bytes.
     * SEEK_CUR - Set position to current location plus offset.
     * SEEK_END - Set position to end-of-file plus offset. (To move to
     * a position before the end-of-file, you need to pass a negative value
     * in offset.)
     * Upon success, returns 0; otherwise, returns -1
     *
     * @param integer $offset
     * @param integer $whence
     * @return integer
     */
    public function seek($offset, $whence=SEEK_SET) {
        ...
    }

    /**
     * Read a $length bytes from the file and advance the file pointer.
     *
     * @param integer $length
     * @return string
     */
    protected function _fread($length=1) {
        ...
    }
}
</pre>

    </div>
</div>
        <hr />

            <table width="100%">
                <tr>
                    <td width="25%" style="text-align: left;">
                    <a href="zend.search.lucene.charset.html">Character Set</a>
                    </td>

                    <td width="50%" style="text-align: center;">
                        <div class="up"><span class="up"><a href="zend.search.lucene.html">Zend_Search_Lucene</a></span><br />
                        <span class="home"><a href="manual.html">Programmer's Reference Guide</a></span></div>
                    </td>

                    <td width="25%" style="text-align: right;">
                        <div class="next" style="text-align: right; float: right;"><a href="zend.search.lucene.java-lucene.html">Interoperating with Java Lucene</a></div>
                    </td>
                </tr>
            </table>
</td>
        <td style="font-size: smaller;" width="15%"> <style type="text/css">
#leftbar {
	float: left;
	width: 186px;
	padding: 5px;
	font-size: smaller;
}
ul.toc {
	margin: 0px 5px 5px 5px;
	padding: 0px;
}
ul.toc li {
	font-size: 85%;
	margin: 1px 0 1px 1px;
	padding: 1px 0 1px 11px;
	list-style-type: none;
	background-repeat: no-repeat;
	background-position: center left;
}
ul.toc li.header {
	font-size: 115%;
	padding: 5px 0px 5px 11px;
	border-bottom: 1px solid #cccccc;
	margin-bottom: 5px;
}
ul.toc li.active {
	font-weight: bold;
}
ul.toc li a {
	text-decoration: none;
}
ul.toc li a:hover {
	text-decoration: underline;
}
</style>
 <ul class="toc">
  <li class="header home"><a href="manual.html">Programmer's Reference Guide</a></li>
  <li class="header up"><a href="manual.html">Programmer's Reference Guide</a></li>
  <li class="header up"><a href="reference.html">Zend Framework Reference</a></li>
  <li class="header up"><a href="zend.search.lucene.html">Zend_Search_Lucene</a></li>
  <li><a href="zend.search.lucene.overview.html">Overview</a></li>
  <li><a href="zend.search.lucene.index-creation.html">Building Indexes</a></li>
  <li><a href="zend.search.lucene.searching.html">Searching an Index</a></li>
  <li><a href="zend.search.lucene.query-language.html">Query Language</a></li>
  <li><a href="zend.search.lucene.query-api.html">Query Construction API</a></li>
  <li><a href="zend.search.lucene.charset.html">Character Set</a></li>
  <li class="active"><a href="zend.search.lucene.extending.html">Extensibility</a></li>
  <li><a href="zend.search.lucene.java-lucene.html">Interoperating with Java Lucene</a></li>
  <li><a href="zend.search.lucene.advanced.html">Advanced</a></li>
  <li><a href="zend.search.lucene.best-practice.html">Best Practices</a></li>
 </ul>
 </td>
    </tr>
</table>

<script type="text/javascript" src="../js/shCore.js"></script>
<script type="text/javascript" src="../js/shAutoloader.js"></script>
<script type="text/javascript" src="../js/main.js"></script>

</body>
</html>